package com.xie.o2o.controller.shopadmin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xie.o2o.dto.ProductExecution;
import com.xie.o2o.entity.Product;
import com.xie.o2o.entity.ProductCategory;
import com.xie.o2o.entity.Shop;
import com.xie.o2o.enums.ProductStateEnum;
import com.xie.o2o.service.ProductCategoryService;
import com.xie.o2o.service.ProductService;
import com.xie.o2o.util.HttpServletUtil;
import com.xie.o2o.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @create: xie
 */
@Controller
@RequestMapping("/shopadmin")
public class ProductManagementController {
    private static final Logger log = LoggerFactory.getLogger(ProductManagementController.class);
    @Autowired
    private ProductService productService;

    @Autowired
    private ProductCategoryService productCategoryService;

    //支持上传的商品详情图最大数量
    private static final int IMAGEMAXCOUNT = 6;


    /**
     * 获取店铺下的商品列表
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getproductlistbyshop", method = RequestMethod.GET)
    public Map<String, Object> getProductListByShop(HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        //获取店铺id和分页数据
        int pageIndex = HttpServletUtil.getInt(request, "pageIndex");
        int pageSize = HttpServletUtil.getInt(request, "pageSize");
        Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
        if ((pageIndex > -1) && (pageSize > -1) && currentShop != null && currentShop.getShopId() != null) {
            //获取传入的赛选条件
            String productName = HttpServletUtil.getString(request, "productName");
            long productCategoryId = HttpServletUtil.getLong(request, "productCategoryId");
            //拼凑product实体类
            Product product = new Product();
            product.setShop(currentShop);
            if (productCategoryId != -1L) {
                ProductCategory productCategory = new ProductCategory();
                productCategory.setProductCategoryId(productCategoryId);
                product.setProductCategory(productCategory);
            }
            if (productName != null) {
                product.setProductName(productName);
            }
            //传入查询条件，返回商品列表和总数量
            ProductExecution productList = productService.getProductList(product, pageIndex, pageSize);
            map.put("productList", productList.getProductList());
            map.put("count", productList.getProductCount());
            map.put("success", true);
        } else {
            map.put("success", false);
            map.put("errMsg", "empty pageSize or pageIndex or shopId");
            return map;
        }
        return map;
    }


    /**
     * 根据商品id返回商品信息和该店铺的商品分类列表，用于修改商品页面
     *
     * @param productId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getproductbyid", method = RequestMethod.GET)
    public Map<String, Object> getProductById(@RequestParam Long productId) {
        Map<String, Object> map = Maps.newHashMap();
        if (productId > -1) {
            //获取商品信息
            Product product = productService.getProductById(productId);
            //获取该店铺下的商品分类列表
            List<ProductCategory> productCategoryList = productCategoryService.queryProductCategoryList(product.getShop().getShopId());
            map.put("product", product);
            map.put("productCategoryList", productCategoryList);
            map.put("success", true);
        } else {
            map.put("success", false);
            map.put("errMsg", "empty productId");
        }
        return map;
    }

    /**
     * 修改商品信息或者上下架操作
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/modifyproduct", method = RequestMethod.POST)
    public Map<String, Object> modifyProduct(HttpServletRequest request) {
        //初始化
        Map<String, Object> map = Maps.newHashMap();
        Product product;
        MultipartFile thumbnailImg = null;
        List<MultipartFile> productImgList = Lists.newArrayList();
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //接受数据
        //如果存在文件流，取出相关文件
        //上传图片是否为空
        if (commonsMultipartResolver.isMultipart(request)) {
            thumbnailImg = getMultipartFile((MultipartHttpServletRequest) request, productImgList);
        } else {
            map.put("success", false);
            map.put("errMsg", "上传图片不能为空");
            return map;
        }
        //获取商品信息，转换成实体类
        String productStr = HttpServletUtil.getString(request, "productStr");
        product = JsonUtil.string2Obj(productStr, Product.class);
        Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
        product.setShop(currentShop);
        if (product != null) {
            try {
                //修改商品信息操作
                ProductExecution pe = productService.modifyProduct(product, thumbnailImg, productImgList);
                if (pe.getState() == ProductStateEnum.SUCCESS.getState()) {
                    map.put("success", true);
                } else {
                    map.put("success", false);
                    map.put("errMsg", pe.getStateInfo());
                }
            } catch (RuntimeException e) {
                log.error("更新商品信息失败:" + e.toString());
                throw new RuntimeException("更新商品信息失败");
            }
        } else {
            map.put("success", false);
            map.put("errMsg", "请输入商品信息");
        }
        return map;
    }

    private MultipartFile getMultipartFile(MultipartHttpServletRequest request, List<MultipartFile> productImgList) {
        MultipartFile thumbnailImg;
        MultipartFile productImg;
        //获取缩略图
        thumbnailImg = request.getFile("thumbnail");
        for (int i = 0; i < IMAGEMAXCOUNT; i++) {
            //循环获取详情图
            productImg = request.getFile("productImg" + i);
            if (productImg != null) {
                //有图片就添加list
                productImgList.add(productImg);
            } else {
                //循环到没有图片停止循环
                break;
            }
        }
        return thumbnailImg;
    }


    /**
     * 添加商品
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addproduct", method = RequestMethod.POST)
    public Map<String, Object> addProduct(HttpServletRequest request) {
        //实体对象初始化
        Map<String, Object> map = Maps.newHashMap();
        //商品信息
        Product product;
        //缩略图
        MultipartFile thumbnailImg;
        //详情图
        List<MultipartFile> productImgList = Lists.newArrayList();
        //接受前端数据
        String productStr = HttpServletUtil.getString(request, "productStr");
        //获取店铺图片
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //上传图片是否为空
        if (commonsMultipartResolver.isMultipart(request)) {
            //获取缩略图
            thumbnailImg = getMultipartFile((MultipartHttpServletRequest) request, productImgList);
        } else {
            map.put("success", false);
            map.put("errMsg", "上传图片不能为空");
            return map;
        }
        //json转换成Product实体类
        product = JsonUtil.string2Obj(productStr, Product.class);
        //如果商品信息、缩略图、商品详情图都不为空，执行添加操作
        if (product != null && thumbnailImg != null && productImgList.size() > 0) {
            try {
                Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
                product.setShop(currentShop);
                ProductExecution productExecution = productService.addProduct(product, thumbnailImg, productImgList);
                if (productExecution.getState() == ProductStateEnum.SUCCESS.getState()) {
                    map.put("success", true);
                } else {
                    map.put("success", false);
                    map.put("errMsg", productExecution.getStateInfo());
                    return map;
                }
            } catch (RuntimeException e) {
                log.error("添加商品失败:" + e.toString());
                throw new RuntimeException("添加商品失败");
            }
        } else {
            map.put("success", false);
            map.put("errMsg", "请输入商品信息");
        }
        return map;
    }

}
